<template>
    <!-- 查询 -->
    <el-card>
        班级名称
        <el-input v-model="form.meetingRoomName" style="width: 180px;" />
        <el-button type="primary" @click="GetList()">查询</el-button>
        <el-button type="primary" @click="add">新增</el-button>
        <el-button type="danger" round @click="PiShan">批量删除</el-button>
        <!-- 显示 -->
        <el-table
    ref="multipleTableRef"
    :data="tableData"
    row-key="id"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection"  width="55" />
            <el-table-column label="会议室名称" align="center">
                <template #default="scope">
                    <div style="display: flex; align-items: center; justify-content: center;">
                        <img
                            v-if="scope.row.photo"
                            :src="scope.row.photo"
                            style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; margin-right: 10px;"
                        />
                        <span>{{ scope.row.meetingRoomName }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="容纳人数" align="center">
                <template #default="scope">
                    {{ capacityToChinese(scope.row.capacityId) }}
                </template>
            </el-table-column>
            <el-table-column label="会议室位置" align="center">
                <template #default="scope">
                    {{ locationToChinese(scope.row.meetingRoomlocationId) }}
                </template>
            </el-table-column>
            <el-table-column prop="adminiStrators" label="管理员" align="center" />
            <el-table-column prop="telephone" label="联系电话" align="center" />
            <el-table-column prop="appointmentApproval" label="预约审批" align="center">
                <template #default="scope">
                    <span v-if="scope.row.appointmentApproval == 1">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column prop="smartMeetingRoom" label="智能会议室" align="center">
                <template #default="scope">
                    <span v-if="scope.row.smartMeetingRoom == 1">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <span class="action-link view" @click="onView(scope.row)">查看</span>
                    <span class="action-link edit" @click="onEdit(scope.row)">修改</span>
                    <span class="action-link delete" @click="Del(scope.row.id)">删除</span>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 分页 -->
    <el-card>
        <table>
            <tbody>
                <tr>
                    <td>
                        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                            :page-sizes="[5, 7, 9, 11]" :background="true" layout="total, slot,sizes"
                            :total="page.totalCount" prev-text="上一页" next-text="下一页">
                            <span>
                                当前{{ page.PageIndex }}页，每页{{ page.totalPage }}/{{ page.PageSize }}条
                            </span>
                        </el-pagination>
                    </td>



                    <td>
                        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                            :page-sizes="[5, 7, 9, 11]" :background="true" layout="slot, prev, pager, next"
                            :total="page.totalCount" prev-text="上一页" next-text="下一页">
                            <span>
                                <el-button type="danger" @click="Shou()">首页</el-button>
                            </span>
                        </el-pagination>
                    </td>




                    <td>
                        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                            :page-sizes="[5, 7, 9, 11]" :background="true" layout="slot,jumper" :total="page.totalCount"
                            prev-text="上一页" next-text="下一页">
                            <span>
                                <el-button type="danger" @click="Wei()">尾页</el-button>
                            </span>
                        </el-pagination>
                    </td>
                </tr>
            </tbody>
        </table>

    </el-card>

    <!-- 添加 -->
    <el-dialog v-model="dialogVisible1" title="新增会议室">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
            <el-form-item label="会议室名称" prop="meetingRoomName">
                <el-input v-model="ruleForm.meetingRoomName" />
            </el-form-item>
            <el-form-item label="容纳人数" prop="capacityId">
                <el-input v-model="ruleForm.capacityId" />
            </el-form-item>
            <el-form-item label="会议室位置" prop="meetingRoomlocationId">
                <el-input v-model="ruleForm.meetingRoomlocationId" />
            </el-form-item>
            <el-form-item label="管理员" prop="adminiStrators">
                <el-input v-model="ruleForm.adminiStrators" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
                <el-input v-model="ruleForm.telephone" />
            </el-form-item>
            <el-form-item label="预约审批">
                <el-radio-group v-model="ruleForm.appointmentApproval">
                    <el-radio-button :label="1">是</el-radio-button>
                    <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="智能会议室">
                <el-radio-group v-model="ruleForm.smartMeetingRoom">
                    <el-radio-button :label="1">是</el-radio-button>
                    <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <!-- 图片上传与预览 -->
            <div style="display: flex; flex-direction: column; align-items: flex-start;">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:5153/api/Images/UploadFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="uploadHeaders"
                    name="file"
                >
                    <img v-if="ruleForm.photo" :src="ruleForm.photo" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div v-if="ruleForm.photo" class="img-remove-btn" @click="removePhoto">×</div>
            </div>
            <el-form-item>
                <el-button type="primary" @click="AddClass(ruleFormRef)">确定</el-button>
                <el-button @click="dialogVisible1 = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="detailDialogVisible" title="会议室详情" width="500px">
        <div style="display: flex; align-items: center; margin-bottom: 20px;">
            <img
                v-if="detailRow.photo"
                :src="detailRow.photo"
                style="width: 80px; height: 80px; object-fit: cover; border-radius: 6px; margin-right: 16px;"
            />
            <span style="font-size: 18px; font-weight: bold;">{{ detailRow.meetingRoomName }}</span>
        </div>
        <el-descriptions :column="1" border>
            <el-descriptions-item label="容纳人数">{{ capacityToChinese(detailRow.capacityId) }}</el-descriptions-item>
            <el-descriptions-item label="会议室位置">{{ locationToChinese(detailRow.meetingRoomlocationId) }}</el-descriptions-item>
            <el-descriptions-item label="管理员">{{ detailRow.adminiStrators }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ detailRow.telephone }}</el-descriptions-item>
            <el-descriptions-item label="预约审批">
                <span v-if="detailRow.appointmentApproval == 1">是</span>
                <span v-else>否</span>
            </el-descriptions-item>
            <el-descriptions-item label="智能会议室">
                <span v-if="detailRow.smartMeetingRoom == 1">是</span>
                <span v-else>否</span>
            </el-descriptions-item>
        </el-descriptions>
        <template #footer>
            <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
    </el-dialog>


  <!-- 修改 -->
  <el-dialog v-model="dialogVisible2" title="修改会议室">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
            <el-form-item label="会议室名称" prop="meetingRoomName">
                <el-input v-model="ruleForm.meetingRoomName" />
            </el-form-item>
            <el-form-item label="容纳人数" prop="capacityId">
                <el-input v-model="ruleForm.capacityId" />
            </el-form-item>
            <el-form-item label="会议室位置" prop="meetingRoomlocationId">
                <el-input v-model="ruleForm.meetingRoomlocationId" />
            </el-form-item>
            <el-form-item label="管理员" prop="adminiStrators">
                <el-input v-model="ruleForm.adminiStrators" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
                <el-input v-model="ruleForm.telephone" />
            </el-form-item>
            <el-form-item label="预约审批">
                <el-radio-group v-model="ruleForm.appointmentApproval">
                    <el-radio-button :label="1">是</el-radio-button>
                    <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="智能会议室">
                <el-radio-group v-model="ruleForm.smartMeetingRoom">
                    <el-radio-button :label="1">是</el-radio-button>
                    <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="会议室图片">
                <div style="display: flex; flex-direction: column; align-items: flex-start;">
                    <el-upload
                        class="avatar-uploader"
                        action="http://localhost:5153/api/Images/UploadFile"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :headers="uploadHeaders"
                        name="file"
                    >
                        <img v-if="ruleForm.photo" :src="ruleForm.photo" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="ruleForm.photo" class="img-remove-btn" @click="removePhoto">×</div>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="UpdateClass(ruleFormRef)">确定</el-button>
                <el-button @click="dialogVisible2 = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import type { FormInstance, FormRules, TableInstance } from 'element-plus'
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router';
import { fa, pa } from 'element-plus/es/locales.mjs';
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs';


const router = useRouter();
const userInfo = useCounterStore();

var tableData = ref([])
// 查询数据
const form = reactive({
    meetingRoomName: ""
})
// 分页数据
const page = reactive({
    totalCount: 0,
    totalPage: 0,
    PageIndex: 1,
    PageSize: 5
})
// 登录
const GetList = () => {
    axios.get("http://localhost:5161/api/Meeting/Handle", {

        params: {
            meetingRoomName: form.meetingRoomName,
            PageSize: page.PageSize,
            PageIndex: page.PageIndex,
        }
    }).then((res) => {
        tableData.value = res.data.data.data
        page.totalCount = res.data.data.totalCount
        page.totalPage = res.data.data.totalPage
    })
}
// 显示
onMounted(() => {
    GetList()
})
//分页
watch(page, () => {
    GetList()
})

const Shou = () => {
    page.PageIndex = 1
    GetList()
}
const Wei = () => {
    page.PageIndex = page.totalPage
    GetList()
}


var dialogVisible1 = ref(false)
var Tips1 = ref("新增班级信息")
const add = () => {
    dialogVisible1.value = true
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "id": 0,
    "photo": "",
    "meetingRoomName": "",
    "capacityId": 0,
    "meetingRoomlocationId": 0,
    "adminiStrators": "",
    "telephone": "",
    "appointmentApproval": 0,
    "smartMeetingRoom": 0,
    "isDeleted": false
})
// 验证
const rules = reactive<FormRules>({
    meetingRoomName: [
        { required: true, message: '会议室名称不能为空', trigger: 'blur' }
    ],
    capacityId: [
        { required: true, message: '容纳人数不能为空', trigger: 'blur' }
    ],
    meetingRoomlocationId: [
        { required: true, message: '会议室位置不能为空', trigger: 'blur' }
    ],
    adminiStrators: [
        { required: true, message: '管理员不能为空', trigger: 'blur' }
    ],
    telephone: [
        { required: true, message: '联系电话不能为空', trigger: 'blur' }
    ]
})

const AddClass = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm)
            axios.post("http://localhost:5153/api/Meeting/Add", ruleForm).then((res) => {
                if (res.data.code == 0) {

                    ElMessage.success("添加成功")
                    dialogVisible1.value = false
                    GetList();
                }
                else {
                    ElMessage.error("添加失败")

                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 容纳人数数字转汉字
function capacityToChinese(val: number | string) {
    if (val === 1 || val === '1') return '一人';
    if (val === 2 || val === '2') return '二人';
    if (val === '11~20人' || val === 11 || val === 20) return '十一至二十人';
    if (val === '21~50人' || val === 21 || val === 50) return '二十一至五十人';
    // 你可以根据实际数据类型和范围继续补充
    return val;
}

// 会议室位置编号转汉字
function locationToChinese(val: number | string) {
    // 这里举例，实际请根据你的数据补充
    if (val === 1 || val === '1') return '一号会议室';
    if (val === 2 || val === '2') return '二号会议室';
    if (val === '办公楼-606') return '办公楼六零六';
    if (val === '办公楼-501') return '办公楼五零一';
    if (val === '办公楼-502') return '办公楼五零二';
    if (val === '办公楼-503') return '办公楼五零三';
    if (val === '行政楼-100') return '行政楼一零零';
    if (val === '行政楼-101') return '行政楼一零一';
    if (val === '行政楼-201') return '行政楼二零一';
    if (val === '行政楼-301') return '行政楼三零一';
    if (val === '行政楼-401') return '行政楼四零一';
    // 你可以根据实际数据类型和范围继续补充
    return val;
}


const detailDialogVisible = ref(false)
const detailRow = ref<any>({})

function onView(row: any) {
    detailRow.value = row
    detailDialogVisible.value = true
}



//删除
const Del = (id: number) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.put("http://localhost:5153/api/Meeting/Del?Id=" + id).then((res) => {
                if (res.data.code == 0) {
                    ElMessage.success("删除成功")
                    GetList()
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}



var dialogVisible2 = ref(false)
var Tips2 = ref("修改班级信息")
const onEdit = (row:any) => {
    dialogVisible2.value = true
    ruleForm.id = row.id
    ruleForm.meetingRoomName = row.meetingRoomName
    ruleForm.capacityId = row.capacityId
    ruleForm.meetingRoomlocationId = row.meetingRoomlocationId
    ruleForm.adminiStrators = row.adminiStrators
    ruleForm.telephone = row.telephone
    ruleForm.appointmentApproval = row.appointmentApproval
    ruleForm.smartMeetingRoom = row.smartMeetingRoom
    ruleForm.isDeleted = row.isDeleted  
    ruleForm.photo = row.photo
}
const UpdateClass = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm)
            axios.put("http://localhost:5153/api/Meeting/Update", ruleForm).then((res) => {
                if (res.data.code == 0) {

                    ElMessage.success("修改成功")
                    dialogVisible2.value = false
                    GetList();
                }
                else {
                    ElMessage.error("修改失败")

                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 上传图片时的请求头（如需token可加上）
const uploadHeaders = {}

// 上传成功回调
function handleAvatarSuccess(response: any) {
    console.log('图片上传返回：', response)
    // 适配不同返回结构
    let url = response?.url || response?.data?.url || response?.data || response
    // 如果是以 / 开头的相对路径，拼接服务器地址
    if (typeof url === 'string' && url.startsWith('/')) {
        url = 'http://localhost:5153' + url
    }
    ruleForm.photo = url
}

// 上传前校验（可选，限制图片类型和大小）
function beforeAvatarUpload(file: File) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    // const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('只能上传 JPG/PNG 格式图片!')
        return false
    }
    // if (!isLt2M) {
    //     ElMessage.error('图片大小不能超过 2MB!')
    //     return false
    // }
    return true
}

// 删除图片
function removePhoto() {
    ruleForm.photo = ''
}

//全选反选操作定义
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<any>([])

function handleSelectionChange(val: any) {
    multipleSelection.value = val;
}

// function toggleSelectAll() {
//     if (multipleSelection.value.length === tableData.value.length) {
//         multipleTableRef.value.clearSelection(); // 反选
//     } else {
//         tableData.value.forEach((row: any) => {
//             meetingTable.value.toggleRowSelection(row, true);
//         });
//     }
// }

const PiShan=()=>{
var ids=[]
multipleSelection.value.forEach(item =>[
    ids.push(item.id)

]);
if(ids.length==0)
{
    ElMessage.warning("请选择要删除的会议室")
    return
}
console.log("ids",ids)

ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.put("http://localhost:5153/api/Meeting/Deleteds",ids).then((res) => {
                if (res.data.code == 0) {
                    ElMessage.success("删除成功")
                    GetList()
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}
</script>

<style scoped>
.action-link {
    margin: 0 6px;
    cursor: pointer;
    font-size: 14px;
}
.action-link.view {
    color: #1890ff;
}
.action-link.edit {
    color: #52c41a;
}
.action-link.delete {
    color: #f5222d;
}
.avatar-uploader .avatar {
    width: 200px;
    height: 200px;
    display: block;
    border-radius: 6px;
    object-fit: cover;
}
.avatar-uploader-icon {
    font-size: 40px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
}
.img-remove-btn {
    position: absolute;
    top: 8px;
    right: 8px;
    background: rgba(0,0,0,0.5);
    color: #fff;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    text-align: center;
    line-height: 24px;
    cursor: pointer;
    font-size: 18px;
}
</style>
